<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\PlanBill;

class PlanbillController extends Controller
{
	public function actionIndex()
	{	
		$query = new \yii\db\Query();

		$displayAll = Yii::$app->request->get("displayAll",0);

		if ($displayAll == 1){
			$list = $query->select("*")->from("JXC_PLANBILL")->orderBy("PLANBILLID DESC")->all();
		}else{
			$list = $query->select("*")->from("JXC_PLANBILL")->orderBy("PLANBILLID DESC")->limit(DEFAULT_LIMIT)->all();
		}

		return $this->render("index",['list' => $list]);
	}

	private function generateQueryString($fieldName){
		if (empty($fieldName))
			return "1 = 1";
		$getFieldNameRequest = $_GET[$fieldName];
		if (empty($getFieldNameRequest))
			return "1 = 1";
		else
			return $fieldName." like '%".$getFieldNameRequest."%'";
	}

	public function actionSearch()
	{	
		$ordernum = $_GET['ordernum'];
		$orderdate = $_GET['orderdate'];
		$orderdate_end = $_GET['orderdate_end'];
		$deliverydate = $_GET['deliverydate'];
		$deliverydate_end = $_GET['deliverydate_end'];

		$query = new \yii\db\Query();

		$query->select("*")
			  ->from("JXC_PLANBILL");

		$queryString = $this->generateQueryString("planbillnum");
		if(!empty($queryString)){
			$query->andWhere($queryString);
		}

		$queryString = $this->generateQueryString("orderunit");
		if(!empty($queryString)){
			$query->andWhere($queryString);
		}

		$queryString = $this->generateQueryString("receivingunit");
		if(!empty($queryString)){
			$query->andWhere($queryString);
		}

		if (!empty($orderdate)) {
			$query->andWhere("orderdate >= '$orderdate'");
		}
		if (!empty($orderdate_end)) {
			$query->andWhere("orderdate <= '".$orderdate_end." 23:59:59'");
		}
		if (!empty($deliverydate)) {
			$query->andWhere("deliverydate >= '$deliverydate'");
		}
		if (!empty($deliverydate_end)) {
			$query->andWhere("orderdate <= '".$deliverydate_end." 23:59:59'");
		}

		if(!empty($ordernum))
		{
			$planbillList = PlanBill::getIdByOrdernum($ordernum);
			$query->andWhere("PLANBILLID in (". $planbillList.")");
		}

		$list = $query->all();
		
		return $this->render("index",['list' => $list]);
	}

	public function actionPlanitem()
	{
		$planbillid = $_GET['id'];

		$query = new \yii\db\Query();
		$list =	$query->select("*")
					  ->from("JXC_PLANBILLITEM")
					  ->where('planbillid = '.$planbillid)
					  ->all();

		$sumCount = 0;
		$sumPrice = 0;
		foreach ($list as  $value) {
			$sumCount += $value['COUNT'];
			$sumPrice += $value['PRICE'];
		}

		return $this->render('item',['list' => $list , 'sumCount'=>$sumCount,'sumPrice'=>$sumPrice]);
	}
}